import cv2
import os
import re
import sys
import numpy as np


class CompressPhoto:
    def __init__(self):
        self.folder_is_true()

    def command(self):
        """
        获取命令行参数
        :return file: 为文件名
        """
        try:
            file = sys.argv[1]
            return file
        except:
            return None

    def folder_is_true(self):
        """
        判断是否存在文件夹(folder)
        :return:
        """
        folder = './new_photo'
        if not os.path.exists(folder):
            os.mkdir(folder)

    def get_all_img_file(self, path='./'):
        """
        获取路径下所有的图片，格式：png/jpeg/jpg
        :param path:
        :return:
        """
        all_file = os.listdir(path)
        img_list = []
        rep = re.compile('.(jpg|jpeg|png|JPG|JPEG|PNG)')
        for file in all_file:
            if rep.findall(file):
                img_list.append(file)
        return img_list

    def file_have_zh(self, file_name):
        """判断文件名中是否有中文"""
        file_is_zh = re.search('[\u4e00-\u9fa5]', file_name)
        img_name = ''
        img_format = ''
        if file_is_zh:
            img_name, img_format = file_name.split('.')  # 将文件进行处理哈
        return img_name, img_format

    def compress_photo(self, file, folder='./new_photo'):
        """
        通过openCV进行对图片压缩处理
        :param file:  文件名
        :param folder:  文件报错路径
        :return:
        """
        img_name, img_format = self.file_have_zh(file)
        if img_name:  # 包含中文字的文件
            new_img_name = f'a.{img_format}'  # 处理后图片名
            img = cv2.imdecode(np.fromfile(file, dtype=np.uint8), -1)
            cv2.imwrite(f'{folder}/{new_img_name}', img, [cv2.IMWRITE_JPEG_QUALITY, 15])
            try:
                os.rename(f'{folder}/{new_img_name}', f'{folder}/new_{img_name}.{img_format}')
                print(f'文件: {file}压缩成功，压缩后的文件名为: new_{file}')
            except FileExistsError as e:
                print(e)
        else:
            new_img_name = f'new_{file}'  # 处理后图片名
            img = cv2.imread(file, cv2.IMREAD_UNCHANGED)
            cv2.imwrite(f'{folder}/{new_img_name}', img, [cv2.IMWRITE_JPEG_QUALITY, 15])
            print(f'文件: {file}压缩成功，压缩后的文件名为: {new_img_name}')

    def new_copress_photo(self, file, folder='./new_photo'):
        pass

    def command_have_file(self):
        """
        命令行中带有一个要处理图片名
        """
        file = self.command()
        self.compress_photo(file)

    def command_have_no_file(self):
        """
        将当前文件夹下所有jpg/jpeg/png图片进行压缩
        :return:
        """
        img_list = self.get_all_img_file()
        for img in img_list:
            self.compress_photo(img)

    def start(self):
        if self.command():
            self.command_have_file()
        else:
            self.command_have_no_file()


if __name__ == '__main__':
    try:
        if sys.argv[1] == '-h':
            print("""
                1.压缩当前所有图片文件(python  c_photo.py)
                2.选择压缩图片(python  c_photo.py  图片名)
                """)
        else:
            CompressPhoto().start()
    except:
        CompressPhoto().start()
